from enum import Enum

from fastapi.requests import Request
from pydantic import conint
from sqlalchemy import select

from utils.drivers.database.engine import AsyncSession
from utils.drivers.database.models.page import Page
from utils.drivers.database.models.page_images import PageImages
from utils.enums import Language
from utils.exception import AppException, StatusCode
from utils.g import G
from utils.i18n.i18n import i18n
from utils.pagination import get_pagination
from utils.template.template import template


class PageTypeEnum(Enum):
    company_profile = "company_profile"
    ceo_speech = "ceo_speech"
    culture = "culture"
    equipment = "equipment"
    certificate = "certificate"


async def about(request: Request, page_type: PageTypeEnum, page: conint(ge=1) = 1):
    stmt = select(Page).where(Page.page == page_type.value).limit(1)  # type: ignore

    try:
        async with AsyncSession() as session:
            async with session.begin():
                page_info = await session.execute(stmt)
                page_info = page_info.scalar()
                type_ = page_info.type
                if not page_info:
                    text = ""
                else:
                    if request.state.language == Language.CN:
                        text = page_info.content
                    else:
                        text = page_info.content_en
    except Exception as e:
        raise AppException(StatusCode.QueryAboutTextError, detail=str(e))

    images = []
    pagination = None
    if type_ == "image":
        images, images_count = await PageImages.get(request.state.language, text, page=page)
        pagination = get_pagination(page, G.pageSize, images_count)

    return template(request, "about.html", context={
        "nav": "about",
        "sub_nav": page_type.value,
        "title": i18n(language=request.state.language, key="navigation_about_us_" + page_type.value),
        "type": type_,
        "text": text,
        "images": images,
        "pagination": pagination
    })
